<?php

/*
 * module page: http://www.prestashop.com/forums/viewthread/27256/
 * @author Gabriel Tenita <info@digitalicon.ro>
 * @copyright Gabriel Tenita
 * @license http://www.opensource.org/licenses/osl-3.0.php Open-source licence 3.0
 * @version 1.2
 */

class BlockYahooStatus extends Module {
	
	function __construct() {
		$this->name = 'blockyahoostatus';
		$this->tab = 'Blocks';
		$this->version = '0.9';

		parent::__construct();

		$this->displayName = $this->l('Yahoo status display block');
		$this->description = $this->l('Adds a block to display the Yahoo status of selected employees');
		$this->confirmUninstall = $this->l('Are you sure you want to uninstall the Yahoo status display block?');
	}

	function install() {
		if (!Db::getInstance()->Execute('CREATE TABLE IF NOT EXISTS '._DB_PREFIX_.'employee_yahoo_status(`id_emp` int(10) NOT NULL,`yahooid` varchar(32), `yahooname` varchar(32),`enabled` tinyint(1) DEFAULT 0,PRIMARY KEY(`id_emp`)) ENGINE=MyISAM default CHARSET=utf8')) return false;
		if (!$this->initTable()) return false;
		if (!parent::install() OR !$this->registerHook('header') OR !$this->registerHook('rightColumn') OR !$this->registerHook('extraRight')) return false;
		return true;
	}

	function uninstall() {
		if (parent::uninstall() == false) return false;
		//if (!Db::getInstance()->Execute('DROP TABLE '._DB_PREFIX_.'employee_yahoo_status')) return false;
		if (!parent::uninstall()) return false;
		return true;
  }
  
  private function initTable() {
  	$eids = DB::getInstance()->ExecuteS('SELECT `id_employee` as id FROM '._DB_PREFIX_.'employee');
	 	if (!$eids) return false;
  	$yids = DB::getInstance()->ExecuteS('SELECT `id_emp` as id FROM '._DB_PREFIX_.'employee_yahoo_status');
 		foreach ($eids as $eid)
 	 		if (!in_array($eid,$yids))
 	 		  $inittable .= '('.$eid['id'].', \'\', \'\', 0),';
 	 	unset($eid);
		if ($inittable) $inittable = Db::getInstance()->Execute(substr_replace('INSERT INTO '._DB_PREFIX_.'employee_yahoo_status VALUES '.$inittable,';',-1,1));
	 	return true;
	}
	
	private function getIDs()	{
	 	if (!$ids = Db::getInstance()->ExecuteS('SELECT `id_employee`, `firstname`, `lastname`, `yahooid`, `yahooname`, `enabled` FROM '._DB_PREFIX_.'employee,'._DB_PREFIX_.'employee_yahoo_status WHERE `id_employee` = `id_emp` ORDER BY `id_employee` ASC')) return false;
	 	return $ids;
	}
	
  private function multiRequest($data, $options = array()) {
    $curly = array();
    $result = array();
    $mh = curl_multi_init();
    foreach ($data as $id => $d) {
      $curly[$id] = curl_init();
      $url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d;
      curl_setopt($curly[$id], CURLOPT_URL,            $url);
      curl_setopt($curly[$id], CURLOPT_HEADER,         0);
      curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1);
      if (is_array($d)) {
        if (!empty($d['post'])) {
          curl_setopt($curly[$id], CURLOPT_POST,       1);
          curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $d['post']);
        }
      }
      if (!empty($options)) {
        curl_setopt_array($curly[$id], $options);
      }
      curl_multi_add_handle($mh, $curly[$id]);
    }
    unset($id,$d);
    $running = null;
    do {
      curl_multi_exec($mh, $running);
    } while($running > 0);
    foreach($curly as $id => $c) {
      $result[$id] = curl_multi_getcontent($c);
      curl_multi_remove_handle($mh, $c);
    }
    unset($id,$c);
    curl_multi_close($mh);
    return $result;
	}

	function getContent() {
	 	$this->_html = '<h2>'.$this->displayName.'</h2>';
	 	if (isset($_POST['submitIDsUpdate'])) {
	 		foreach ($_POST as $key => $value) {
 	 			if ($key != 'submitIDsUpdate') {
 	 				$yii = substr($key,strpos($key,'_')+1);
 	 				$yif = substr($key,0,strpos($key,'_'));
 				  $emps[$yii]['id_emp'] = $yii;
 				  $emps[$yii][$yif] = $value;
	 			}
 	 		}
 	 		unset($key,$value);
 	 		$emps = array_values($emps);
 			$errmsg[1] = $this->l('Bad Yahoo ID.');
 			$errmsg[2] = $this->l('You cannot enable an employee without an Yahoo ID.');
 			$errmsg[3] = $this->l('Yahoo name').' '.$this->l('must be a... name!');
 			$errmsg[4] = $this->l('Yahoo name').' '.$this->l('must not be empty.');
   	 	foreach ($emps as $emp) {
	 			if (!Validate::isPasswd($emp['yahooid'],0))
	 			  $err[1][] = $emp['id_emp'];
  	 		if (!$emp['yahooid'] AND $emp['enabled'])
  	 		  $err[2][] = $emp['id_emp'];
	 			if (!Validate::isGenericName($emp['yahooname'],0))
	 			  $err[3][] = $emp['id_emp'];
  	 		if (!$emp['yahooname'] AND $emp['enabled'])
  	 		  $err[4][] = $emp['id_emp'];
	 		}
	 		unset($emp);
  	  $ids = $this->getIDs();
			if (!$err) {
   	 	  foreach ($emps as $id => $emp) {
 	 		    $emp['enabled'] = $emp['enabled'] ? '1' : '0';
 	 		    if ($emp['yahooid'] != $ids[$id]['yahooid'] OR $emp['yahooname'] != $ids[$id]['yahooname'] OR $emp['enabled'] != $ids[$id]['enabled'])
    	 	    if (!Db::getInstance()->AutoExecute(_DB_PREFIX_.'employee_yahoo_status', $emp, 'UPDATE', '`id_emp` = '.intval($emp['id_emp'])))
    	 	      return false;
  		  }
		 		unset($emp);
  		} 		
  		else {
  		  foreach ($err as $key => $val)
  			  $this->_html .= $this->displayError($errmsg[$key]).'<p>'.$this->l('Problems at the following IDs:').' '.implode(', ', $val).'.</p><br />';
	 	 		unset($key,$value);
	 	 	}
  		if (!$err) $this->_html .= $this->displayConfirmation($this->l('The Yahoo status list was updated successfully.'));
 	 	  //$this->updTable($empsupd);
  	}
	 	if (isset($_POST['submitYSPUpdate'])) {
    	if (!Validate::isGenericName($_POST['yscta1']))
    		$err[3] = '1, ';
   		if (!Validate::isGenericName($_POST['yscta2']))
    		$err[3] .= '2, ';
    	if (!Validate::isGenericName($_POST['yscta3']))
    		$err[3] .= '3, ';
  		if ($err[3]) $this->_html .= $this->displayError($this->l('Characters not allowed.')).'<p>Problems at the following fields: '.substr_replace($err[3],'.',-2,2).'</p>';
    	else {
    		$options = array('YAHOO_STATUS_CTA_1','YAHOO_STATUS_CTA_2','YAHOO_STATUS_CTA_3');
    		$conf = Configuration::getMultiple($options);
    		foreach ($options as $option)
   				$conf[$option] = $conf[$option] ? $conf[$option] : '';
    		unset($option);
    		$i=1;
    		foreach ($conf as $c) {
    			if ($_POST['yscta'.$i] != $c or !empty($_POST['yscta'.$i])) {
    				Configuration::updateValue('YAHOO_STATUS_CTA_'.$i, ($_POST['yscta'.$i]));
    				$i++;
    			}
    		}
    		unset($c);
  			$this->_html .= $this->displayConfirmation($this->l('The Call-To-Action contacts were updated successfully.'));
			}
		}
  	if (isset($_POST['submitIDsExport'])) {
  		$errors = '';
  		$newCsv .= '\'id_employee\',\'firstname\',\'lastname\',\'yahooid\',\'yahooname\',\'enabled\''."\n";
  	  $ids = $this->getIDs();
  		foreach ($ids as $key => $field) {
  			foreach ($field as $key => $value)
  				$newCsv .= $value.',';
  			$newCsv .= "\n";
  		}
  		unset($key,$field);
  		$ysfn = 'ysbackup'.date('ymdHi').'.csv';
  		if ($fd = @fopen(dirname(__FILE__).'/'.$ysfn, 'w')) {
  			if (!@fwrite($fd, $newCsv))
  				$errors .= $this->displayError($this->l('Unable to write to the export file.'));
  			if (!@fclose($fd))
  				$errors .= $this->displayError($this->l('Can\'t close the export file.'));
  		}
  		else
  			$errors .= $this->displayError($this->l('Unable to update the export file.').'<br />'.$this->l('Please check the export file\'s writing permissions.'));
  		if ($errors == '')
  			$this->_html .= $this->displayConfirmation($this->l('The Yahoo status list was exported successfully to').' '.dirname(__FILE__).$ysfn.'.');
	 	}
	 	$this->_html .= '<br /><img src="'.$this->_path.'img/thumb.gif" style="float:left; margin:0 15px 16px 0;">'.$this->l('This module allows you to display the Yahoo status of employees in the Front Office and your customer to initiate a instant messaging session.').'<br class="clear" />
		<form class="width5" method="post" action="'.$_SERVER['REQUEST_URI'].'">
			<fieldset>
				<legend><img src="'.$this->_path.'logo.gif" alt="" title="" /> '.$this->l('Display Yahoo Status').'</legend><br />
				<table class="table">
					<thead>
						<tr>
							<th>'.$this->l('ID').'</th>
							<th>'.$this->l('First Name').'</th>
							<th>'.$this->l('Last Name').'</th>
							<th>'.$this->l('Yahoo ID').'</th>
							<th>&rArr; '.$this->l('Change to:').'</th>
							<th>'.$this->l('Yahoo name').'</th>
							<th>&rArr; '.$this->l('Change to:').'</th>
							<th>'.$this->l('Enabled').'</th>
							<th>&rArr; '.$this->l('Change to:').'</th>
						</tr>
					</thead>
					<tbody>';$alt = false;
		    $ids = $this->getIDs();
				foreach ($ids as $id => $status) {
					$yid = $emps[$id]['yiid'] ? $emps[$id]['yiid'] : $status['yahooid'];
					$ynm = $emps[$id]['yinm'] ? $emps[$id]['yinm'] : $status['yahooname'];
					$yen = $emps[$id]['yien'] ? $emps[$id]['yien'] : $status['enabled'];
					$this->_html .= '<tr';
					$this->_html .= $alt ? ' class="alt_row"' : '';
					$this->_html .= '>
						<td>'.$status['id_employee'].'</td>
						<td>'.$status['firstname'].'</td>
						<td>'.$status['lastname'].'</td>
						<td class="bold">'.$status['yahooid'].'</td>
						<td><input type="text" name="yahooid_'.$status['id_employee'].'" class="yahooid" value="'.$yid . '" /></td>
						<td class="bold">'.$status['yahooname'].'</td>
						<td><input type="text" name="yahooname_'.$status['id_employee'].'" class="yahooname" value="'.$ynm . '" /></td>';
					$this->_html .= '<td class="center">';
					$this->_html .= $status['enabled'] ? '<img title="'.$this->l('Enabled').'" alt="'.$this->l('Active').'" src="'._PS_ADMIN_IMG_.'enabled.gif"/>' : '<img title="'.$this->l('Disabled').'" alt="'.$this->l('Inactive').'" src="'._PS_ADMIN_IMG_.'disabled.gif"/>';
					$this->_html .= '</td>';
					$this->_html .= '<td class="center"><input type="checkbox" name="enabled_'.$status['id_employee'].'" class="enabled"';
					$this->_html .= $yen ? ' checked="checked"' : '';
					$this->_html .= ' /></td>
					</tr>';
					$alt = !$alt;
				}
				unset($id,$status);
				$this->_html .= '
				 	</tbody>
				</table><br />
				</p><input type="submit" class="button" name="submitIDsUpdate" value="'.$this->l('Update Yahoo status list').'" /></p>
			</fieldset>
		</form>
		<br />
		<form class="width5" method="post" action="'.$_SERVER['REQUEST_URI'].'">
			<fieldset>
				<legend><img src="'.$this->_path.'img/cta.gif" alt="" title="" /> '.$this->l('Call-to-action contacts').'</legend>
				<p>'.$this->l('Here you can put additional contact methods.').'<br />'.$this->l('Please note that, unlike the Yahoo IDs, these are not clickable.').'<br />'.$this->l('If you want to place a phone/e-mail/fax/whatever order call-to-action near the Yahoo status, enter at least the first item:').'</p>
				<table class="table">
					<thead>
						<tr>
							<th>#</th>
							<th>Call-to-action contact</th>
						</tr>
					</thead>
					<tbody>
						<tr>
							<td>1.</td>
							<td><input type="text" name="yscta1" value="'.Configuration::get('YAHOO_STATUS_CTA_1').'" /></td>
						</tr>
						<tr class="alt_row">
							<td>2.</td>
							<td><input type="text" name="yscta2" value="'.Configuration::get('YAHOO_STATUS_CTA_2').'" /></td>
						</tr>
						<tr>
							<td>3.</td>
							<td><input type="text" name="yscta3" value="'.Configuration::get('YAHOO_STATUS_CTA_3').'" /></td>
						</tr>
					</tbody>
				</table><br />
				<input type="submit" class="button" name="submitYSPUpdate" value="'.$this->l('Update contact fields').'" />
			</fieldset>
		</form>
		<br />
		<form class="width1" method="post" action="'.$_SERVER['REQUEST_URI'].'">
			<fieldset>
			<legend><img src="'.$this->_path.'img/export.gif" alt="" title="" /> '.$this->l('Export Yahoo status list').'</legend>
			<p><input type="submit" class="button" name="submitIDsExport" value="'.$this->l('Export Yahoo IDs list to a .csv file').'" /></p>
			</fieldset>
		</form>';
		return $this->_html;
	}
	
	function hookHeader($params)
	{
		return $this->display(__FILE__, 'header.tpl');
	}

	
	function hookRightColumn($params) {
		
		global $smarty;
		$host = 'http://opi.yahoo.com/online';
		
	 	$ydata = $this->getIDs();
	 	if (!$ydata) return false;
	 	
	 	foreach ($ydata as $y) {
 			if ($y['enabled']) {
				$yenab[] = $y;
				$opi[] = $host.'?u='.$y['yahooid'].'&m=t&t=1';
			}
		}
		unset($y);
		$opis = $this->multiRequest($opi);
		$i=0;
		foreach ($yenab as $y) {
			$yenab[$i]['status'] = $opis[$i] == '01' ? 'on' : 'off';
			$i++;
		}
		unset($y);
		
		$smarty->assign('yahooids',$yenab);
		$arrayConf = array('YAHOO_STATUS_CTA_1','YAHOO_STATUS_CTA_2','YAHOO_STATUS_CTA_3');
		$conf = Configuration::getMultiple($arrayConf);
		$i=1;
		foreach ($conf as $c) {
			if ($c != '')
				$smarty->assign('yscta'.$i++, $c);
		}
		unset($c);

		//$smarty->debugging=true;
		return $this->display(__FILE__, 'blockyahoostatus.tpl');
	}

	function hookLeftColumn($params)
	{
		return $this->hookRightColumn($params);
	}

	function hookExtraRight($params)
	{
		return $this->hookRightColumn($params);
	}

	function hookTop($params)
	{
		$this->hookRightColumn($params);
		return $this->display(__FILE__, 'blockyahoostatus-top.tpl');
	}
}

?>